<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/needsharebutton/needsharebutton.css">

















  
  
  <link rel="stylesheet" href="/xieyuanhui/lib/fancybox/source/jquery.fancybox.css">







<link rel="stylesheet" href="/xieyuanhui/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/xieyuanhui/css/main.css?v=7.1.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/xieyuanhui/images/apple-touch-icon-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/xieyuanhui/images/favicon-32x32-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/xieyuanhui/images/favicon-16x16-next.png?v=7.1.0">


  <link rel="mask-icon" href="/xieyuanhui/images/logo.svg?v=7.1.0" color="#222">


  <link rel="manifest" href="/xieyuanhui/images/manifest.json">


  <meta name="msapplication-config" content="/xieyuanhui/images/browserconfig.xml">





<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/xieyuanhui/',
    scheme: 'Pisces',
    version: '7.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="原文地址：记spring-boot项目启动卡住问题排查记录 问题一问题背景一个spring boot开发的项目，spring boot版本是1.5.7，携带的spring版本是4.1.3。开发反馈，突然在本地启动不起来了，表象特征就是在本地IDEA上运行时，进程卡住也不退出，应用启动时加载相关组件的日志也不输出。症状如下图：  问题分析因为没有有用的日志信息，所以不能从日志这个层面上排查问题。但是">
<meta name="keywords" content="解决方案">
<meta property="og:type" content="article">
<meta property="og:title" content="项目中遇到的困难以及解决方案">
<meta property="og:url" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/index.html">
<meta property="og:site_name" content="xieyuanhui的笔记">
<meta property="og:description" content="原文地址：记spring-boot项目启动卡住问题排查记录 问题一问题背景一个spring boot开发的项目，spring boot版本是1.5.7，携带的spring版本是4.1.3。开发反馈，突然在本地启动不起来了，表象特征就是在本地IDEA上运行时，进程卡住也不退出，应用启动时加载相关组件的日志也不输出。症状如下图：  问题分析因为没有有用的日志信息，所以不能从日志这个层面上排查问题。但是">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img1.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img2.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img3.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img4.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img5.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img6.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img7.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img8.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img9.jpg">
<meta property="og:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/D:/Blog/source/_posts/项目中遇到的困难以及解决方案/img10.jpg">
<meta property="og:updated_time" content="2019-07-18T13:24:27.134Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="项目中遇到的困难以及解决方案">
<meta name="twitter:description" content="原文地址：记spring-boot项目启动卡住问题排查记录 问题一问题背景一个spring boot开发的项目，spring boot版本是1.5.7，携带的spring版本是4.1.3。开发反馈，突然在本地启动不起来了，表象特征就是在本地IDEA上运行时，进程卡住也不退出，应用启动时加载相关组件的日志也不输出。症状如下图：  问题分析因为没有有用的日志信息，所以不能从日志这个层面上排查问题。但是">
<meta name="twitter:image" content="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img1.jpg">



  <link rel="alternate" href="/xieyuanhui/atom.xml" title="xieyuanhui的笔记" type="application/atom+xml">



  
  
  <link rel="canonical" href="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>项目中遇到的困难以及解决方案 | xieyuanhui的笔记</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/xieyuanhui/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xieyuanhui的笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/xieyuanhui/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/xieyuanhui/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/xieyuanhui/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/xieyuanhui/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/xieyuanhui/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xyh5513.gitee.io/xieyuanhui/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xieyuanhui">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/xieyuanhui/images/deer.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xieyuanhui的笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">项目中遇到的困难以及解决方案

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-07-04 09:24:18" itemprop="dateCreated datePublished" datetime="2019-07-04T09:24:18+08:00">2019-07-04</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-07-18 21:24:27" itemprop="dateModified" datetime="2019-07-18T21:24:27+08:00">2019-07-18</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/xieyuanhui/categories/项目/" itemprop="url" rel="index"><span itemprop="name">项目</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          
            <span id="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/" class="leancloud_visitors" data-flag-title="项目中遇到的困难以及解决方案">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">14k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">13 分钟</span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>原文地址：<a href="https://www.cnblogs.com/qwangxiao/p/10981911.html" target="_blank" rel="noopener">记spring-boot项目启动卡住问题排查记录</a></p>
<h2 id="问题一"><a href="#问题一" class="headerlink" title="问题一"></a>问题一</h2><h3 id="问题背景"><a href="#问题背景" class="headerlink" title="问题背景"></a>问题背景</h3><p>一个spring boot开发的项目，spring boot版本是1.5.7，携带的spring版本是4.1.3。开发反馈，突然在本地启动不起来了，表象特征就是在本地IDEA上运行时，进程卡住也不退出，应用启动时加载相关组件的日志也不输出。症状如下图：</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img1.jpg" alt></p>
<h3 id="问题分析"><a href="#问题分析" class="headerlink" title="问题分析"></a>问题分析</h3><p>因为没有有用的日志信息，所以不能从日志这个层面上排查问题。但是像这种没有输出日志的话，一般情况下，肯定是程序内部启动流程卡在什么地方了，只能通过打印下当前线程堆栈信息了解下。一般情况下，在服务器环境，我们会使用java工具包中的jstack 工具来查看：如jstack pid（应用java进程）。</p>
<p>但是，在IDEA本地开发的话，IDEA内置了一个工具，可以直接查看当前应用的线程上线文信息，如：</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img2.jpg" alt></p>
<p>注意下面那个箭头指向的像照相机一样的图标，故图思意，就是打印当前线程快照的的意思。点击后，就出现了右边那些线程上下文信息了，可以看到有很多的线程，我们主要关注下main线程，线程状态确实是waiting的，接着点击箭头所指向的main线程，可以看到如下内容：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"main@1"</span> prio=<span class="number">5</span> tid=<span class="number">0x1</span> nid=NA waiting</span><br><span class="line">java.lang.Thread.State: WAITING</span><br><span class="line">at sun.misc.Unsafe.park(Unsafe.java:-<span class="number">1</span>)</span><br><span class="line">at java.util.concurrent.locks.LockSupport.park(www.ztyLegw.cn  LockSupport.java:<span class="number">175</span>)</span><br><span class="line">at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:<span class="number">836</span>)</span><br><span class="line">at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:<span class="number">997</span>)</span><br><span class="line">at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:<span class="number">1304</span>)</span><br><span class="line">at java.util.concurrent.CountDownLatch.await(www.wanhaoptdL.com CountDownLatch.java:<span class="number">231</span>)</span><br><span class="line">at org.springframework.boot.autoconfigure.BackgroundPreinitializer.onApplicationEvent(BackgroundPreinitializer.java:<span class="number">63</span>)</span><br><span class="line">at org.springframework.boot.autoconfigure.BackgroundPreinitializer.onApplicationEvent(BackgroundPreinitializer.java:<span class="number">45</span>)</span><br><span class="line">at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:<span class="number">172</span>)</span><br><span class="line">at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:<span class="number">158</span>)</span><br><span class="line">at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:<span class="number">139</span>)</span><br><span class="line">at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:<span class="number">127</span>)</span><br><span class="line">at org.springframework.boot.context.event.EventPublishingRunListener.finished(EventPublishingRunListener.java:<span class="number">115</span>)</span><br><span class="line">at org.springframework.boot.SpringApplicationRunListeners.www.tcgjgw.<span class="function">com <span class="title">callFinishedListener</span><span class="params">(SpringApplicationRunListeners.java:<span class="number">79</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.SpringApplicationRunListeners.<span class="title">finished</span><span class="params">(SpringApplicationRunListeners.java:<span class="number">72</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.SpringApplication.<span class="title">handleRunFailure</span><span class="params">(SpringApplication.java:<span class="number">745</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.SpringApplication.<span class="title">run</span><span class="params">(SpringApplication.java:<span class="number">314</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.builder.SpringApplicationBuilder.<span class="title">run</span><span class="params">(SpringApplicationBuilder.java:<span class="number">134</span>)</span></span></span><br><span class="line"><span class="function">- locked &lt;0xea6&gt; <span class="params">(a java.util.concurrent.atomic.AtomicBoolean)</span></span></span><br><span class="line"><span class="function">at org.springframework.cloud.bootstrap.BootstrapApplicationListener.www.chaoyuL.com <span class="title">bootstrapServiceContext</span><span class="params">(BootstrapApplicationListener.java:<span class="number">175</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.cloud.bootstrap.BootstrapApplicationListener.<span class="title">onApplicationEvent</span><span class="params">(BootstrapApplicationListener.java:<span class="number">98</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.cloud.bootstrap.BootstrapApplicationListener.<span class="title">onApplicationEvent</span><span class="params">(BootstrapApplicationListener.java:<span class="number">64</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.context.event.SimpleApplicationEventMulticaster.<span class="title">doInvokeListener</span><span class="params">(SimpleApplicationEventMulticaster.java:<span class="number">172</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.context.event.SimpleApplicationEventMulticaster.<span class="title">invokeListener</span><span class="params">(SimpleApplicationEventMulticaster.java:<span class="number">165</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.context.event.SimpleApplicationEventMulticaster.<span class="title">multicastEvent</span><span class="params">(SimpleApplicationEventMulticaster.java:<span class="number">139</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.context.event.SimpleApplicationEventMulticaster.<span class="title">multicastEvent</span><span class="params">(SimpleApplicationEventMulticaster.java:<span class="number">127</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.context.event.EventPublishingRunListener.<span class="title">environmentPrepared</span><span class="params">(EventPublishingRunListener.java:<span class="number">74</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.SpringApplicationRunListeners.<span class="title">environmentPrepared</span><span class="params">(SpringApplicationRunListeners.java:<span class="number">54</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.SpringApplication.<span class="title">prepareEnvironment</span><span class="params">(SpringApplication.java:<span class="number">325</span>)</span></span></span><br><span class="line"><span class="function">at org.springframework.boot.SpringApplication.<span class="title">run</span><span class="params">(SpringApplication.java:<span class="number">296</span>)</span></span></span><br><span class="line"><span class="function">at cn.keking.project.customerManagement.KekingCustomerManagement.<span class="title">main</span><span class="params">(KekingCustomerManagement.java:<span class="number">36</span>)</span></span></span><br></pre></td></tr></table></figure>
<p>可以看到是通过CountDownLatch.await()阻塞了线程，接着看下面那行，所在代码块如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> CountDownLatch preinitializationComplete = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</span><br><span class="line"> </span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onApplicationEvent</span><span class="params">(SpringApplicationEvent event)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (event <span class="keyword">instanceof</span> ApplicationEnvironmentPreparedEvent) &#123;</span><br><span class="line">      <span class="keyword">if</span> (preinitializationStarted.compareAndSet(<span class="keyword">false</span>, <span class="keyword">true</span>)) &#123;</span><br><span class="line">         performPreinitialization();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">if</span> (event <span class="keyword">instanceof</span> ApplicationReadyEvent |www.chengmyuLegw.cn| event <span class="keyword">instanceof</span> ApplicationFailedEvent) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         preinitializationComplete.await();</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (InterruptedException ex) &#123;</span><br><span class="line">         Thread.currentThread(www.cmylwg.com/).interrupt();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是spring boot中的一个安全初始化资源的一个类，代码所示为监听SpringApplicationEvent事件，可以肯定的是，它的逻辑执行到了 preinitializationComplete.await();这里，导致了线程阻塞了。正常情况下，spring会触发ApplicationEnvironmentPreparedEvent事件完成资源的初始化，这里先不深究Spring为什么这么做，主要通过程序逻辑看下为什么卡这里了，在preinitializationComplete.await();所在行打个断点，看下event对象里的信息，如下：</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img3.jpg" alt></p>
<p>原来event是一个Spring上下文初始化失败的异常事件对象，对象里包含了具体的异常信息，如箭头所指，关键异常信息如：</p>
<p>NoSuchMethodError：”org.springframework.util.ObjectUtils.unwrapOptional(Ljava/lang/Object;)Ljava/lang/Object;”</p>
<h3 id="假设问题"><a href="#假设问题" class="headerlink" title="假设问题"></a>假设问题</h3><p>通过上面的分析，基本定位到Spring boot应用启动卡住这个表象背后的真实原因了，而且也定位到了异常信息。</p>
<p>出现NoSuchMethodError异常，是因为调用方法的时候，找不到方法了。一般出现在两个有关联的jar包，但是版本对不上了，也就是常说的jar版本依赖冲突。查看了下，ObjectUtils是spring-core包里的一个类，当前的4.1.3版本确实没有这个unwrapOptional方法，spring-core-5.x的版本才新增了这个方法。因为之前的依赖是没有问题，为什么现在spring上下文会调用5.x的版本的方法呢？</p>
<p>所以先假设近期有开发在pom.xml里添加了新的的依赖，导致了这个问题。</p>
<h3 id="小心求证"><a href="#小心求证" class="headerlink" title="小心求证"></a>小心求证</h3><p>有了找问题的方向就好办了，因为代码都是git管理维护的，所以查看下pom.xml文件近期的提交记录即可，查看后，确实发现了近期对pom.xml有改动，添加了一个依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-context<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.6.RELEASE<span class="tag">&lt;<span class="name">www.yuntianyuL.cn</span> /<span class="attr">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>这里还涉及到一点Maven依赖优先级的问题，在pom.xml里直接这样添加的依赖优先于其他jar中pom.xml依赖的，也就是说，即使spring boot1.5.7自带了Spring-context.4.1.3，但是这样指定后，应用最后依赖的还是5.1.6的版本。具体的Maven依赖关系，可以参考我的博文《关于Maven的使用，这些你都了解了么？》。结合之前的分析，八九不离十了就是因为加了这个依赖导致的问题，spring-context.5.1.6配合spring-core.4.1.3肯定得出问题啊。直接移除这个依赖，然后启动系统一切正常，日志打印了Spring加载上线文的信息。</p>
<h3 id="问题总结"><a href="#问题总结" class="headerlink" title="问题总结"></a>问题总结</h3><p>这里还涉及到一点Maven依赖优先级的问题，在pom.xml里直接这样添加的依赖优先于其他jar中pom.xml依赖的，也就是说，即使spring boot1.5.7自带了Spring-context.4.1.3，但是这样指定后，应用最后依赖的还是5.1.6的版本。具体的Maven依赖关系，可以参考我的博文《关于Maven的使用，这些你都了解了么？》。结合之前的分析，八九不离十了就是因为加了这个依赖导致的问题，spring-context.5.1.6配合spring-core.4.1.3肯定得出问题啊。直接移除这个依赖，然后启动系统一切正常，日志打印了Spring加载上线文的信息。</p>
<p>原文地址：<a href="https://mp.weixin.qq.com/s?__biz=MzA3NDcyMTQyNQ==&amp;mid=2649262158&amp;idx=1&amp;sn=877406536ba246f224e71a1b66196066&amp;chksm=876759b0b010d0a6408b6a4ad9594578895c3ac0463e5856be78ae3bfb1cdf77674c029c9f90&amp;mpshare=1&amp;scene=1&amp;srcid=0714fVE0krU8YsFpaOrbAkjV&amp;key=60109a54bfe7ef6f567ab221dc7129254efe0c3de197f4d82e8899f940e76d2a0c6a64fe0bd2ecb3bfa1de66829aa8af4e20feec03fd17342a402e6fb3fd0b0d47901cd210c559f79d1f4c9a1f8353e8&amp;ascene=1&amp;uin=MTg0MTc0ODU4NA%3D%3D&amp;devicetype=Windows+10&amp;version=62060833&amp;lang=zh_CN&amp;pass_ticket=AzbzTSbaAlRccRP8xMCe44hFQ4wppM8A3F0J3wMulyXqAifX2kpLYjCvR3SNAavt" target="_blank" rel="noopener">记一次CLOSE_WAIT问题排查</a></p>
<h2 id="问题二"><a href="#问题二" class="headerlink" title="问题二"></a>问题二</h2><h3 id="现象"><a href="#现象" class="headerlink" title="现象"></a>现象</h3><p>应用出现告警。</p>
<p>观察程序日志出现大量<em>org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool。</em></p>
<p>初步判断是 httpclient 连接池满了导致无法获取新连接。</p>
<h3 id="问题排查"><a href="#问题排查" class="headerlink" title="问题排查"></a>问题排查</h3><h4 id="初探"><a href="#初探" class="headerlink" title="初探"></a>初探</h4><p>httpclient 连接池满了，首先想到的是某些连接请求时间比较长，并且没有设置合理的超时时间，导致被占满，如果假设成立，则集群中的其它机器也应该会出现这种错误，但是从监控和其它机器的日志看，并没有出现连接池被占满的情况。</p>
<h4 id="换个思路"><a href="#换个思路" class="headerlink" title="换个思路"></a>换个思路</h4><p>既然是单台机器的问题，直接登录到机器上观察网络连接，发现大量的连接停留在 CLOSE_WAIT 上，并且网络对端是集群中各个机器，包括这台机器本身，端口是 8080 ，而且数量正好是 200 ，跟代码中 httpclient 配置的连接池最大数量相符，截止到目前，可以断定是由于这些未关闭的连接占满了连接池，所以后续的请求都无法获取连接了。</p>
<p><strong>还有一个点需要注意，每一个 CLOSE_WAIT 的连接中都有 1 个字节的数据未被接收，这一点后续会有说明。</strong> </p>
<p>那 CLOSE_WAIT 什么情况下会产生呢？这就要说到 TCP 的连接和断开，贴个经典的图:</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img4.jpg" alt></p>
<p>这张图我修改了一下，在断开连接的时候，更符合文章中说的这个 case ，remote 和 local 角色交换了一下，为什么会是这样，我们后面说。</p>
<p>从上图中我们可以看到，<strong>CLOSE_WAIT 状态产生的时机，在服务端发送了 FIN 包之后，客户端返回 ACK ，这时候客户端的 TCP 连接就处于 CLOSE_WAIT 状态。</strong>然后是这样，那就说明客户端没有发送 FIN 包，也就是没有主动关闭连接。</p>
<h3 id="柳暗花明"><a href="#柳暗花明" class="headerlink" title="柳暗花明"></a>柳暗花明</h3><p>既然是代码问题，从监控中找出问题机器产生 CLOSE_WAIT 的时间点，扒一下应用在那个时间点的发布记录，比较幸运，应用的那次发布并没有改动太多，很容易就定位到了问题代码，贴一部分代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">keep</span><span class="params">(String url)</span></span>&#123;</span><br><span class="line">    log.info(<span class="string">"url &#123;&#125;"</span>, url);</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        HttpPost httpPost = <span class="keyword">new</span> HttpPost(url);</span><br><span class="line">        <span class="keyword">final</span> CloseableHttpResponse response = httpClient.execute(httpPost);</span><br><span class="line">        log.info(<span class="string">"result:&#123;&#125;"</span>, response);</span><br><span class="line">    &#125; <span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">        log.warn(<span class="string">"error"</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到代码很简单，就是一个普通的 HTTP 访问，对端返回的是空响应体，状态码是 200 ，看起来一切都很正常。为了验证是否为这段代码引起的，在测试环境手工触发了这段代码，果然会产生 CLOSE_WAIT ，现在可以断定，就是这段代码引起的。</p>
<h3 id="究其原因"><a href="#究其原因" class="headerlink" title="究其原因"></a>究其原因</h3><p>既然是客户端未发送 FIN 包，那就是 response 并没有关闭，可以看到，代码中直接打印了 response 后，并没有做任何操作。这也解释了为什么 CLOSE_WAIT 中都会有 1 个字节的数据未被接收，那一个字节的数据应该就是 EOF 。</p>
<h3 id="修复"><a href="#修复" class="headerlink" title="修复"></a>修复</h3><p>既然知道了原因，那需要手动接收 response 中流数据，并将其关闭，代码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">keep</span><span class="params">(String url)</span></span>&#123;</span><br><span class="line">    log.info(<span class="string">"url &#123;&#125;"</span>, url);</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        HttpPost httpPost = <span class="keyword">new</span> HttpPost(url);</span><br><span class="line">        <span class="keyword">final</span> CloseableHttpResponse response = httpClient.execute(httpPost);</span><br><span class="line">        <span class="keyword">final</span> HttpEntity entity = response.getEntity();</span><br><span class="line">        String resBody = EntityUtils.toString(entity);</span><br><span class="line">        log.info(<span class="string">"result:&#123;&#125;"</span>, resBody);</span><br><span class="line">    &#125; <span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">        log.warn(<span class="string">"error"</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里有一点需要注意，<strong>必须要调用 EntityUtils.toString() 方法将 HttpEntity 对象转成字符串</strong>，因为关闭流的方法在这里面。贴出来相关的代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">toString</span><span class="params">(HttpEntity entity, Charset defaultCharset)</span> <span class="keyword">throws</span> IOException, ParseException </span>&#123;</span><br><span class="line">    Args.notNull(entity, <span class="string">"Entity"</span>);</span><br><span class="line">    <span class="comment">// 获取entity中的流</span></span><br><span class="line">    InputStream instream = entity.getContent();</span><br><span class="line">    <span class="keyword">if</span> (instream == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 此处省略一些代码</span></span><br><span class="line">        Reader reader = <span class="keyword">new</span> InputStreamReader(instream, defaultCharset);</span><br><span class="line">        CharArrayBuffer buffer = <span class="keyword">new</span> CharArrayBuffer(i);</span><br><span class="line">        <span class="keyword">char</span>[] tmp = <span class="keyword">new</span> <span class="keyword">char</span>[<span class="number">1024</span>];</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">int</span> l;</span><br><span class="line">        <span class="keyword">while</span> ((l = ((InputStreamReader) reader).read(tmp)) != -<span class="number">1</span>) &#123;</span><br><span class="line">            buffer.append(tmp, <span class="number">0</span>, l);</span><br><span class="line">        &#125;</span><br><span class="line">        String var9 = buffer.toString();</span><br><span class="line">        <span class="keyword">return</span> var9;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 关闭流</span></span><br><span class="line">        instream.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>改动的代码上线后，问题顺利解决。</p>
<h3 id="扩展阅读"><a href="#扩展阅读" class="headerlink" title="扩展阅读"></a>扩展阅读</h3><h4 id="为什么服务端主动关闭连接？"><a href="#为什么服务端主动关闭连接？" class="headerlink" title="为什么服务端主动关闭连接？"></a>为什么服务端主动关闭连接？</h4><p>理论上来说，都是客户端主动关闭连接，如果不关闭的话，应该保持 ESTABLISH 状态，为什么 tomcat 会主动断开连接呢？</p>
<p>我们知道 http 协议是无状态的，在 http1.0 的时候，客户端和服务端的连接每次在服务端传输完数据之后就会被关闭，但是看了一下 tomcat 的 server.xml 配置，是 http1.1 协议的，那既然是这样，应该默认是支持长连接，除非客户端在请求头中的 Connection 字段指定了 close ，但是在代码中并没有发现显式的指定。</p>
<p>为了测试，在本地用 Spring boot 创建了一个很简单的 demo ，启动之后，用 http client 客户端访问，依然是模拟出现问题的代码，就是不关闭 response ，发现 TCP 连接一直是 establish 的状态，访问测试服务器上的应用，却可以复现 CLOSE_WAIT ，那问题可能是出现在 tomcat 的配置上，于是乎，仔细翻看 tomcat 的各项配置，终于在 server.xml 里面找到了可疑点。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Connector</span> <span class="attr">port</span>=<span class="string">"8080"</span> <span class="attr">protocol</span>=<span class="string">"HTTP/1.1"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">maxThreads</span>=<span class="string">"200"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">connectionTimeout</span>=<span class="string">"20000"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">enableLookups</span>=<span class="string">"false"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">compression</span>=<span class="string">"on"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">redirectPort</span>=<span class="string">"8443"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">URIEncoding</span>=<span class="string">"UTF-8"</span></span></span><br><span class="line"><span class="tag">        </span></span><br><span class="line"><span class="tag">        <span class="attr">compressableMimeType</span>=<span class="string">"text/csv,text/html,text/xml,text/css,text/plain,text/javascript,application/javascript,application/x-javascript,application/json,application/xml"</span></span></span><br><span class="line"><span class="tag">/&gt;</span></span><br></pre></td></tr></table></figure>
<p>从 tomcat 的官方文档中可以找到两条配置的说明:</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img5.jpg" alt></p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img6.jpg" alt></p>
<p>因为服务器并没有设置 keepAliveTimeout ，所以采用的就是 connectionTimeout 的配置，也就是 20 秒如果没有请求就会关闭连接，于是乎，把本地创建的 demo 中的 tomcat 设置为 5 秒关闭，再次请求本地的测试代码，不出意外，出现了 CLOSE_WAIT 的连接。</p>
<h4 id="为什么服务端不会有大量FIN-WAIT2的连接？"><a href="#为什么服务端不会有大量FIN-WAIT2的连接？" class="headerlink" title="为什么服务端不会有大量FIN_WAIT2的连接？"></a>为什么服务端不会有大量FIN_WAIT2的连接？</h4><p>再回过去看 TCP 的那张图，可以发现，如果客户端在 CLOSE_WAIT 状态，那服务端应该是在 FINWAIT2 状态，从上面的本地 demo 也可以证明这一点，那为什么服务端并没有积压很多这种连接呢？</p>
<p>从服务器的连接历史监控数据可以看到，其它服务端确实会出现 FINWAIT2 状态的 TCP 连接，但是都不会积压很久，系统会回收掉，其实这种 FIN 状态的连接，是通过 Linux 的 TCP 参数配置来设置超时时间的，超过了配置的超时时间，就会被系统回收掉，只需要通过 sysctl 命令设置 net.ipv4.tcpfin_timeout 参数来设置超时回收时间即可，单位是秒，服务端设置的是 30 秒，所以这些 FIN 状态的 TCP 连接会存在最多 30 秒就被系统回收了。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>至此，所有问题和疑点都已经解决，通过这次 CLOSE_WAIT 的问题排查，可以总结出来一些套路，大家遇到相关问题的时候，可以按照套路排查问题。</p>
<p>1.CLOSE_WAIT 根本的原因是应用端未关闭一个已经被对端关闭的连接导致，所以我们可以翻看代码中发起 HTTP 请求的地方，如果请求的系统比较多，可以通过 netstat 等相关命令查看 tcp 的对端地址和端口，来辅助查找。</p>
<p>2.找到对应的代码之后，可以看代码的处理逻辑，如果是判断响应码为 200 再进行业务处理的情况，观察如果响应码不为 200 的话，是否有主动关闭流，可以使用 httpRequest.abort() 来关闭，这里可以通过被调用方的 access 日志来辅助判断，如下是一个符合这条 case 的 demo ，首先我们需要一个很简单的 web 服务，只需要返回非 200 的状态码即可，然后模拟未关闭流的情况。</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img7.jpg" alt></p>
<p>执行完上述代码，如果 tomcat 设置的 keepAlive 时间比较短的话，就可以从本机看到 CLOSE_WAIT 状态的 TCP 连接了，同样，如果服务端只是返回了 200 的状态码，但是未返回内容，在本机业务处理的时候没有把 Entity 转为 String 的话，即跟本文章中的 case 一样，也会出现 CLOSE_WAIT 状态的 TCP 连接，所以遇到这种情况，需要对非 200 的状态码进行单独的关闭。</p>
<p>3.如果响应码是 200 ，再看业务代码是否处理出现异常，这里的异常包括各种 Exception ，或者多线程导致的各种问题，如未使用线程安全类导致的死循环等，在异常出现的时候，是否有捕获并关闭流，对于线程安全问题导致的死循环，很明显的一个特征就是某个 CPU 核心的使用率是 100% ，可以通过 mpstat 或 top 命令查看出现问题的线程栈。</p>
<p>4.还有一种情况，业务处理和 IO 处理在同一个线程，要注意在处理 IO 的过程中，是否会产生各种异常，或者多线程导致的问题，如未使用线程安全类导致的死循环等，对于异常，可以使用 finally 来关闭流，对于死循环这种问题，明显的一个特征就是某个 CPU 核心的使用率是 100% ，可以通过 mpstat 或 top 命令查看出现问题的线程栈，下面是模拟一个死循环导致未关闭流的情况：</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img8.jpg" alt></p>
<p>这段代码是故意模拟的一个死循环，实际代码中有可能是由于非线程安全类导致，由于在处理 IO 过程中产生了死循环，所以没有关闭流，导致系统里面产生了 CLOSE_WAIT 的 TCP 连接，同时，使用 top 观察 cpu 使用情况，可以看到其中一个线程 CPU 使用率 100% ，因为测试代码是单线程，所以直接看到 main 线程是 100% 。</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/img9.jpg" alt></p>
<p>另外，还可以从一些蛛丝马迹中来帮助我们定位问题，比如文章中的这个 case ，所有 CLOSE_WAIT 的未接收数据都是 1 字节，大概率是未主动关闭流导致，如果是不相等的字节数，可能是应用处理到某处出现问题，比如上面提到的异常或死循环等。</p>
<h2 id="问题三"><a href="#问题三" class="headerlink" title="问题三"></a>问题三</h2><p>我们都知道,如果你想要通过@Autowired注入一个对象,那么前提是当前你所在的这个类本身需要被Spring管理, 举个例子: 你想要在一个Controller里注入一个Service,那么不仅这个Service要贴上@Service,这个Controller也要贴上@Controller, 如果当前的Controller并未贴上@Controller,那就无法注入,因为Spring并未管理当前Controller的生命周期.</p>
<p>重点来了,如果我的一个Service A明明已经贴上了注解,另一个Service B也贴上了注解,而且都被扫描到了,那为什么还是无法通过@Autowired注入呢?</p>
<p>现在有两个类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> LitheLight</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/7/18</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomUserService</span> <span class="keyword">implements</span> <span class="title">UserDetailsService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    UserDao userDao;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserDetails <span class="title">loadUserByUsername</span><span class="params">(String s)</span> <span class="keyword">throws</span> UsernameNotFoundException </span>&#123;</span><br><span class="line">        SysUser sysUser = userDao.findByUsername(s);</span><br><span class="line">        <span class="keyword">if</span> (sysUser == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UsernameNotFoundException(<span class="string">"用户名不存在"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        List&lt;SimpleGrantedAuthority&gt; authorities = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (SysRole role : sysUser.getRoles()) &#123;</span><br><span class="line">            authorities.add(<span class="keyword">new</span> SimpleGrantedAuthority(role.getName()));</span><br><span class="line">            log.info(role.getName());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> User(sysUser.getUsername(), sysUser.getPassword(), authorities);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> LitheLight</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/7/18</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserDao</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Select</span>(<span class="string">"select u.*, r.name from sys_user u left join sys_role_user sru on u.id=sru.sys_user_id"</span> +</span><br><span class="line">            <span class="string">" left join sys_role r on sru.sys_role_id=r.id where username=#&#123;username&#125;"</span>)</span><br><span class="line">    <span class="function">SysUser <span class="title">findByUsername</span><span class="params">(@Param(<span class="string">"username"</span>)</span> String username)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到UserDao和CustomUserService都已经被Spring容器管理了，但是运行时报错:</p>
<p><img src="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/D:/Blog\source\_posts\项目中遇到的困难以及解决方案\img10.jpg" alt></p>
<p>可以看到UserDao仍然为空，说明注入失败。</p>
<p>原理其实很简单, 在CustomUserService里要调用findByUsername的方法,首先CustomUserService这个类就要从容器中拿,而不能直接new出来,因为交给Spring管理的类一般默认是单例的,它会为这个对象注入属性,但自己new出来的类,就不会注入这个属性了,而我拿到的CustomUserService实现类其实就是我自己new出来的.</p>
<p>解决办法：从容器中取出CustomUserService</p>

      
    </div>

    

    
    
    

    
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script>
  <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css">
 
  <p><span>本文标题:</span>项目中遇到的困难以及解决方案</p>
  <p><span>文章作者:</span>xieyuanhui</p>
  <p><span>发布时间:</span>2019年07月04日 - 09:24:18</p>
  <p><span>最后更新:</span>2019年07月18日 - 21:24:27</p>
  <p><span>原始链接:</span><a href="/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/" title="项目中遇到的困难以及解决方案">http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://xyh5513.gitee.io/xieyuanhui/2019/07/04/项目中遇到的困难以及解决方案/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-SA 4.0</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    clipboard.on('success', $(function(){
      $(".fa-clipboard").click(function(){
        swal({   
          title: "",   
          text: '复制成功',   
          html: false,
          timer: 500,   
          showConfirmButton: false
        });
      });
    }));  
</script>

    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>您的支持将鼓励我继续创作</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/wechatpay.png" alt="xieyuanhui 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/xieyuanhui/images/alipay.jpg" alt="xieyuanhui 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/xieyuanhui/tags/解决方案/" rel="tag"># 解决方案</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
              <div id="needsharebutton-postbottom">
                <span class="btn">
                  <i class="fa fa-share-alt" aria-hidden="true"></i>
                </span>
              </div>
            
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/xieyuanhui/2019/07/01/哈夫曼树和哈夫曼编码/" rel="next" title="哈夫曼树和哈夫曼编码">
                <i class="fa fa-chevron-left"></i> 哈夫曼树和哈夫曼编码
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/xieyuanhui/2019/07/08/生产者-消费者问题/" rel="prev" title="生产者--消费者问题">
                生产者--消费者问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/xieyuanhui/images/deer.png" alt="xieyuanhui">
            
              <p class="site-author-name" itemprop="name">xieyuanhui</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/xieyuanhui/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/xieyuanhui/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/xieyuanhui/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">114</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/xieyuanhui/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/xieyuanhui/yuanhxie@163.com" title="E-Mail &rarr; yuanhxie@163.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#问题一"><span class="nav-text">问题一</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#问题背景"><span class="nav-text">问题背景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#问题分析"><span class="nav-text">问题分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#假设问题"><span class="nav-text">假设问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小心求证"><span class="nav-text">小心求证</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#问题总结"><span class="nav-text">问题总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#问题二"><span class="nav-text">问题二</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#现象"><span class="nav-text">现象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#问题排查"><span class="nav-text">问题排查</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#初探"><span class="nav-text">初探</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#换个思路"><span class="nav-text">换个思路</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#柳暗花明"><span class="nav-text">柳暗花明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#究其原因"><span class="nav-text">究其原因</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修复"><span class="nav-text">修复</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#扩展阅读"><span class="nav-text">扩展阅读</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#为什么服务端主动关闭连接？"><span class="nav-text">为什么服务端主动关闭连接？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#为什么服务端不会有大量FIN-WAIT2的连接？"><span class="nav-text">为什么服务端不会有大量FIN_WAIT2的连接？</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#问题三"><span class="nav-text">问题三</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xieyuanhui</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">749k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:21</span>
  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.1.0</div>


<div><span id="sitetime"></span>
<script language="javascript">
  function siteTime(){
    window.setTimeout("siteTime()", 1000);
    var seconds = 1000;
    var minutes = seconds * 60;
    var hours = minutes * 60;
    var days = hours * 24;
    var years = days * 365;
    var today = new Date();
    var todayYear = today.getFullYear();
    var todayMonth = today.getMonth()+1;
    var todayDate = today.getDate();
    var todayHour = today.getHours();
    var todayMinute = today.getMinutes();
    var todaySecond = today.getSeconds();
    /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
    year - 作为date对象的年份，为4位年份值
    month - 0-11之间的整数，做为date对象的月份
    day - 1-31之间的整数，做为date对象的天数
    hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
    minutes - 0-59之间的整数，做为date对象的分钟数
    seconds - 0-59之间的整数，做为date对象的秒数
    microseconds - 0-999之间的整数，做为date对象的毫秒数 */
    var t1 = Date.UTC(2019,04,09,15,00,00); //北京时间2018-2-13 00:00:00
    var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
    var diff = t2-t1;
    var diffYears = Math.floor(diff/years);
    var diffDays = Math.floor((diff/days)-diffYears*365);
    var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
    var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
    var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
    document.getElementById("sitetime").innerHTML=" xieyuanhui的个人笔记已运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
  }/*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
  siteTime();
</script></div>



<div>

  <div class="theme-info">
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
  </div>

</div>

        






  <div>
    <script type="text/javascript">
	    var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
	    document.write(unescape("%3Cspan id='cnzz_stat_icon_1277235632'%3E%3C/span%3E%3Cscript 
	    src='" + cnzz_protocol + "s23.cnzz.com/z_stat.php%3Fid%3D1277235632%26show%3Dpic' 
	    type='text/javascript'%3E%3C/script%3E"));
    </script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  
    
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/xieyuanhui/lib/canvas-nest/canvas-nest.min.js"></script>













  
  <script src="/xieyuanhui/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/xieyuanhui/lib/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script src="/xieyuanhui/js/utils.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/motion.js?v=7.1.0"></script>



  
  


  <script src="/xieyuanhui/js/affix.js?v=7.1.0"></script>

  <script src="/xieyuanhui/js/schemes/pisces.js?v=7.1.0"></script>



  
  <script src="/xieyuanhui/js/scrollspy.js?v=7.1.0"></script>
<script src="/xieyuanhui/js/post-details.js?v=7.1.0"></script>



  


  <script src="/xieyuanhui/js/next-boot.js?v=7.1.0"></script>


  

  

  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/xieyuanhui/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'q2BU0OM2W8i5nARddHRKQOvm-gzGzoHsz',
                'X-LC-Key': 'hLTPk12Jmt8atnC9cePjTwQH',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });
  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') { next = next.nextSibling }
        if (next && next.nodeName.toLowerCase() === 'br') { next.parentNode.removeChild(next) }
      }
    });
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      document.getElementById(all[i].inputID + '-Frame').parentNode.className += ' has-jax';
    }
  });
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>

    
  


  

  

  

  

  
  
  
  <script src="/xieyuanhui/lib/needsharebutton/needsharebutton.js"></script>
  <script>
    
      pbOptions = {};
      
        pbOptions.iconStyle = "box";
      
        pbOptions.boxForm = "horizontal";
      
        pbOptions.position = "bottomCenter";
      
        pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
        flOptions.iconStyle = "box";
      
        flOptions.boxForm = "horizontal";
      
        flOptions.position = "middleRight";
      
        flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>


  

  

  

  

  

  


  
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({"tex2jax":{"inlineMath":[["$","$"],["\\(","\\)"]],"skipTags":["script","noscript","style","textarea","pre","code"],"processEscapes":true},"TeX":{"equationNumbers":{"autoNumber":"AMS"}}});
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->
  
</body>
</html>
